package com.baomidou.kisso.my.filter;

import com.baomidou.kisso.SSOConfig;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.Token;
import com.baomidou.kisso.common.util.HttpUtil;
import com.baomidou.kisso.web.filter.SSOFilter;
import com.jims.master.common.utils.CacheUtils;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.security.SystemAuthorizingRealm;
import com.jims.master.modules.sys.utils.UserUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.logging.Logger;

public class MySSOFilter extends SSOFilter {
    private static final Logger logger = Logger.getLogger("SSOFilter");
    private static String OVERURL = null;
    @Override
    public void init(FilterConfig config) throws ServletException {
        /**
         * 从应用 web.xml 配置参数中
         * 获取不需要拦截URL
         */
        OVERURL = config.getInitParameter("over.url");
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        boolean isOver = HttpUtil.inContainURL(req, OVERURL);
        StringBuffer requestURL = req.getRequestURL();
        if (!(requestURL.indexOf("/proxylogin") > 0 || requestURL.indexOf("/oklogin") > 0)){
            /** 非拦截URL、安全校验Cookie */
            if (!isOver) {
                Token token = SSOHelper.getToken(req);
                SystemAuthorizingRealm.Principal principal = UserUtils.getPrincipal();
                if (token == null && principal==null) {
                    /**
                     * 清除用户
                     */
                    User user=UserUtils.getUser();
                    UserUtils.clearCache(UserUtils.getUser());
                    CacheUtils.remove("orgStaff_" + user.getId());
                    /**
                     * 重新登录
                     */
                    logger.fine("logout. request url:" + req.getRequestURL());
                    SSOHelper.getKissoService();
                    String ip=request.getLocalAddr();
                    String loginUrl = "";
                    if(ip.indexOf("192.168")!=-1){
                        loginUrl=SSOConfig.getSSOProperties().get("sso.login.local.url");
                    }else{
                        loginUrl=SSOConfig.getSSOProperties().get("sso.login.url");
                    }
                    /**
                     * 获取访问地址组织登录地址
                     */
                    String path = req.getContextPath();
                    String retUrl= req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+path+"/"+ URLEncoder.encode(SSOConfig.getSSOProperties().get("sso.defined.proxylogin"));
                    session.setAttribute("returnUrl",requestURL);
                    res.sendRedirect(HttpUtil.encodeRetURL(loginUrl, "ReturnURL", retUrl));
                    return;
                } else {
                    req.setAttribute(SSOConfig.SSO_TOKEN_ATTR, token);
                }
            }
        }
        chain.doFilter(request, response);

    }


}
